<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    .box1 {
      position: absolute;
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }
    .box2 {
      position: absolute;
      top: 300px;
      width: 200px;
      height: 200px;
      background-color: red;
    }
  </style>
  <body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
      var box1 = document.querySelector(".box1");
      var box2 = document.querySelector(".box2");

      function drag(obj) {
        obj.onmousedown = function () {
          //div的偏移量 鼠标.clientX(pageX) - 元素.offsetLeft
          //div的偏移量 鼠标.clientY(pageY) - 元素.offsetTop
          var ol = event.pageX - obj.offsetLeft;
          var ot = event.pageY - obj.offsetTop;
          document.onmousemove = function () {
            //获取鼠标的坐标
            var left = event.pageX - ol;
            var top = event.pageY - ot;

            //修改box1的位置
            obj.style.left = left + "px";
            obj.style.top = top + "px";

            return false;
          };
        };

        obj.onmouseup = function () {
          document.onmousemove = null;
        };
        //   document.onmouseup = function () {
        //     document.onmousemove = null;
        //     document.onmouseup = null;
        //     alert("111");
        //   };

        // obj.onmousemove = function () {
        //   event.cancelBubble = true;
        // };
      }
      drag(box1);
      drag(box2);
      /* 当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容
           此时会导致拖拽功能的异常,这个是浏览器提供的默认行为
           如果不希望发现这个行为,则可以通过return false来取消默认行为
           IE8不支持
        */
    </script>
  </body>
</html>
